/**
 *    @file       server.h
 *
 *    @brief      
 *    @details
 *
 *    @version    1.0
 *    @date       02/10/2014 03:28:30 PM
 *
 *    @author     Theophilus (), wangtf418@gmail.com
 */
#ifndef _SF_SERVER_H_
#define _SF_SERVER_H_
#include "srvdef.h"
#include "message.h"
#include "classfactory.h"
#include "threadgroup.h"
#include "globaltime.h"
#include "baseconf.h"

class workthread;

class server
{
protected:
	server();
	virtual ~server();

public:
	template<typename _Tsrv>
	static inline bf_int_t create()
	{
		if (!m_instance)
		{
			m_instance = new _Tsrv();
		}
		return BF_OK;
	}

	static inline bf_int_t destroy()
	{
		if (m_instance)
		{
			delete m_instance;
			m_instance = NULL;
		}
		return BF_OK;
	}

	static inline server * get()
	{
		return  m_instance;
	}

public:
	virtual bf_int_t init();
	virtual bf_int_t start();
	virtual void process_cycle();
	void write_messageq_state(bf_int_t logtype);
	
public:
	bf_int_t register_threadgrp(threadgroup *group);
	inline classfactory * get_classfactory() {return m_classfactory;}
	inline globaltime & get_globaltime() {return m_globaltime;}
	inline void set_time(bf_time_t curtime) {m_globaltime.settime(curtime);}
	inline bf_time_t get_time() {return m_globaltime.get_unixtime();}
	inline baseconf & get_baseconf() {return m_baseconf;}

public:
	inline void put_msg(message *msg)
	{
		if (!msg) return;
		msghead &head = msg->get_msghead();
		if (head.m_thd_type >= MAX_THREAD_TYPE)
		{
			delete msg;
			return;
		}
		if (!m_threadgroup[head.m_thd_type])
		{
			delete msg;
			return;
		}
		m_threadgroup[head.m_thd_type]->put_msg(msg);
		return;
	}

protected:
	virtual bf_int_t init_signal();
	static void sighandler(bf_int_t signum);
	virtual bf_int_t init_log();

protected:
	static server *m_instance;

protected:
	classfactory *m_classfactory;
	threadgroup *m_threadgroup[MAX_THREAD_TYPE];
	globaltime m_globaltime;
	baseconf m_baseconf;
};

#endif

